<?php
/*
Module Group: text
Module Group Name: 文本
Description: 这是一个用来处理文本信息的插件
Version: 1.0
Display: 0
Iconurl: http://www.happyidea.com.cn/resource/wx_icon/text.png
Author: snaill
Modules: text
*/
class imageModule extends Module {
	public function run($message, $material, $userStatus) {
		$materialObj = simplexml_load_string($material->xml,
				'SimpleXMLElement', LIBXML_NOCDATA);
		$rm = $message->reply(message_type_image);
		if($material->media_id){
			$rm->media_id = (String)$material->media_id;
		}else{
			Module::callModule("messageSearch",null,"getMaterialCount",NULL);
			$materialModel = D("material");
			$id = $material->id;
			$materialObj=$materialObj->Articles->item;
			$result = self::saveFile((String)$materialObj->picUrl,message_type_image);
			$file_info=array(
				'filename'=>$result['path'], //国片相对于网站根目录的路径
				'content-type'=>$result['content-type'], //文件类型
				'filelength'=>$result['size'] //图文大小
			);
			$path = $result['path'];
			$result = WeixinApi::add_material("image",$file_info);
			@unlink($path);
			$result = json_decode($result,true);
			$materialModel->where("id=$id")->setField("media_id",$result['media_id']);
			$rm->media_id = $result['media_id'];
		}
		if(!empty($material->accessTag) && !empty($message->fromUserName)){	
			 setAccessTags($material->accessTag,$message->fromUserName,module_handle_text, $message->id);
		}
		return $rm;
	}
	public function saveFile($path,$type) {
		$fileName = pathinfo($path);
		$image_name = strToLower($fileName['basename']);
		$ch = curl_init ($path);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
		$img = curl_exec ($ch);
		curl_close ($ch);
		$fp = fopen($image_name,'w');
		fwrite($fp, $img);
		fclose($fp);
		if($type=='image'&&filesize($image_name)>=2048000){
			self::resizejpg($image_name,2000,$image_name);
		}
		$result['size'] = filesize($image_name);
		$result['path']=$image_name;
		$result['content-type']=$type."/".$fileName['extension'];
		return $result;
	}
	function resizejpg($imgsrc,$undersize,$savepath)
	{						//输出格式
		$arr = getimagesize($imgsrc);    						//获取源文件的长宽信息
		$size = filesize($imgsrc);
		$size = ceil($size/1024);       						//计算源文件的大小(kb)
		$percentum = $undersize / $size; 						//变成原来的多少
		if($size <= $undersize){								//已经满足的照片则不予处理
			return ;
		}
		$dest_area = $arr[0]*$arr[1]*$percentum;          		//转换之后的面积
		$newpercent = sqrt($dest_area/($arr[0]*$arr[1])); 		//长宽变化的比率
		$imgWidth = $arr[0]*$newpercent; 			       		//计算出来的宽缩放后的宽度
		$imgHeight = $arr[1]*$newpercent; 				  		//计算出来的高缩放后的高度

		// Create image and define colors
		$imgsrc = imagecreatefromjpeg($imgsrc);
		$image = imagecreatetruecolor($imgWidth, $imgHeight);   //创建一个彩色的底图
		imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth,$imgHeight,$arr[0], $arr[1]);
		imagejpeg($image,$savepath);        				    //保存jpg格式图片
		imagedestroy($image);
	}

}

$module = new imageModule();
Module::addModule($module);